<template>
    <el-table :data="filterTableData" class="table">
      <el-table-column label="申请时间" prop="applyTime" />
      <el-table-column label="申请账号" prop="account" />
      <el-table-column label="真实姓名" prop="realName" />
      <el-table-column label="工作部门" prop="department" />
      <el-table-column label="申请内容" prop="applyDesc" />
      <el-table-column label="申请用途" prop="applyReason" />
      <el-table-column>
        <template #header>
          <el-input v-model="search" size="small" placeholder="输入关键字进行搜索" />
        </template>
        <template #default="scope">
          <el-button
            type="success"
            @click="handleApproval(scope.$index, scope.row)"
            v-loading="approvalLoading && loadingAccount.indexOf(tableData[scope.$index].account) !== -1">通过</el-button>
          <el-button
            type="danger" 
            @click="handleReject(scope.$index, scope.row)"
            v-loading="rejectLoading && loadingAccount.indexOf(tableData[scope.$index].account) !== -1">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogShow" :title="dialogTitle" width="400">
        <el-input v-model.trim="approvalDesc" 
            placeholder="请填写100字以内的审批意见"
            maxlength="100"
            show-word-limit/>
        <template #footer>
            <el-button @click="clickDialogCancel">取消</el-button>
            <el-button type="primary" @click="clickDialogConfirm">确定</el-button>
        </template>
    </el-dialog>
  </template>

<script setup lang='ts' name='ApplyApproval'>
    import { ref, reactive, computed, onMounted } from "vue";
    import request from "@/requests/request"
    import { ElMessage } from "element-plus";
    import moment from "moment";


    let dialogShow = ref(false)
    let approvalType = ref<number>(1)
    const dialogTitle = computed(()=> {
        if (approvalType.value === 1) {
            return "同意申请"
        } else {
            return "拒绝申请"
        }
    })
    let approvalDesc = ref<string>("")

    interface ApplyItem {
        id: number,
        applyTime: string,
        account: string,
        realName: string,
        department: string,
        applyType: number,
        applyVolume: number,
        applyDesc: string,
        applyReason: string,
    }

    const tableData = reactive<Array<ApplyItem>>([])
    let loadingAccount = reactive<Array<string>>([])
    
    let clickIndex : number = -1
    let clickRow: any = null
    
    const search = ref('')
    const filterTableData = computed(() =>
        tableData.filter(
        (data) =>
            !search.value ||
            data.realName.toLowerCase().includes(search.value.toLowerCase())
        )
    )


    function clickDialogConfirm(){
        if (approvalType.value === 1) {
            doApproval(clickIndex, clickRow)
        } else {
            if(approvalDesc.value.length > 0) {
                doReject(clickIndex, clickRow)
            } else {
                ElMessage('审批意见不能为空')
                return
            }
        }
        dialogShow.value = false
    }

    function clickDialogCancel() {
        dialogShow.value = false
    }

    const approvalLoading = ref(false)
    const handleApproval = (index: number, row: ApplyItem) => {
        dialogShow.value = true
        approvalType.value = 1
        approvalDesc.value = ""
        clickIndex = index
        clickRow = row
    }

    function doApproval(index: number, row: ApplyItem) {
        console.log("doApproval", index, row)
        approvalLoading.value = true
        loadingAccount.push(tableData[index].account)
        const data = {
            "id": tableData[index].id,
            "applyStatus": 2, // 从申请完成状态修改成审批通过状态(1--->2)
            "applyVolume": tableData[index].applyVolume,
            "approvalDesc": approvalDesc.value,
            "applyType": tableData[index].applyType,
        }
        request.post("/approveApply", data).then((res: any) => {
            approvalLoading.value = false
            loadingAccount = loadingAccount.filter((account: string) => {
                account !== tableData[index].account
            })
            const { data, message, resCode } = res.data
            ElMessage({
                message: message,
                type: data ? 'success' : 'error',
            })
            if (data) {
                tableData.splice(index, 1)
            }
            console.log(data, message, resCode)
        }).catch((reason: any) => {
            approvalLoading.value = false
            loadingAccount = loadingAccount.filter((account: string) => {
                account !== tableData[index].account
            })
            ElMessage({
                message: "审批申请状态失败",
                type: 'error',
            })
            console.log(reason)
        })
    }


    const rejectLoading = ref(false)
    const handleReject = (index: number, row: ApplyItem) => {
        dialogShow.value = true
        approvalType.value = 2
        approvalDesc.value = ""
        clickIndex = index
        clickRow = row
    }
    function doReject(index: number, row: ApplyItem) {
        console.log("handleReject", index, row)
        rejectLoading.value = true
        loadingAccount.push(tableData[index].account)
        const data = {
            "id": tableData[index].id,
            "applyStatus": 3, // 从申请完成状态修改成申请拒绝状态(1--->3)
            "approvalDesc": approvalDesc.value
        }
        request.post("/rejectApply", data).then((res: any) => {
            rejectLoading.value = false
            loadingAccount = loadingAccount.filter((account: string)=> {
                account !== tableData[index].account
            })
            const {data, message, resCode} = res.data
            ElMessage({
              message: message,
              type: data ? 'success' : 'error',
            })
            if (data) {
              tableData.splice(index, 1)
            }
            console.log(data, message, resCode)
        }).catch((reason: any) => {
            loadingAccount = loadingAccount.filter((account: string)=> {
                  account !== tableData[index].account
              })
            rejectLoading.value = false
            ElMessage({
              message: "拒绝申请状态失败",
              type: 'error',
            })
            console.log(reason)
        })
    }
    
    onMounted(()=> {
        const formData = new FormData()
        formData.append("applyStatus", "1") // 申请完成, 但还未审批
        const headers = {
            ContentType: "application/x-www-form-urlencoded",
        }
        request.post("/queryApplyRecordByStatus", formData, {headers}).then((res: any) => {
            const objArray = JSON.parse(res.data.data)
            if (objArray.length > 0) {
                for(const element of objArray) {
                    const applyTime = moment(element.applyTime).format("YYYY-MM-DD HH:mm:ss")
                    const item: ApplyItem = {
                        id: element.id,
                        applyTime,
                        account: element.account,
                        realName: element.realName,
                        department: element.department,
                        applyType: element.applyType,
                        applyVolume: element.applyVolume,
                        applyDesc: element.applyType === 1 ? `新建${element.applyVolume}GB`: `扩容${element.applyVolume}GB`,
                        applyReason: element.applyReason
                    };
                    tableData.push(item)
                }
            }
        }).catch((reason: any) => {
            console.log(reason)
        })
    })

</script>

<style scoped lang='scss'>

</style>